package com.settlement.system.service.impl;

import com.alibaba.excel.util.DateUtils;
import com.settlement.system.common.enums.ChannelEnum;
import com.settlement.system.mapper.*;
import com.settlement.system.model.entity.common.OtherCapitalStatistics;
import com.settlement.system.model.entity.common.OtherCapitalStatisticsParam;
import com.settlement.system.model.entity.common.TblRrOtherCapitalDetail;
import com.settlement.system.service.OtherCapitalDetailRefreshService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.ParseException;
import java.util.*;

/**
 * 其他货币资金日记账刷新类
 * @author user
 */
@Service
public class OtherCapitalDetailRefreshServiceImpl implements OtherCapitalDetailRefreshService {

    private static Map<String, String> channalNoVBillTypeNameMap = null;

    private static TblRrOtherCapitalDetail EMPTY_OTHER_CAPITAL;

    static {
        channalNoVBillTypeNameMap = new HashMap<>(16);
        channalNoVBillTypeNameMap.put(ChannelEnum.JD.getNo(), "钱包流水");
        channalNoVBillTypeNameMap.put(ChannelEnum.TM.getNo(), "天猫账单明细");
        channalNoVBillTypeNameMap.put(ChannelEnum.OR.getNo(), "线下打款明细");
        channalNoVBillTypeNameMap.put(ChannelEnum.YG.getNo(), "优购网（支付宝）账单明细");

        EMPTY_OTHER_CAPITAL = new TblRrOtherCapitalDetail();
        //EMPTY_OTHER_CAPITAL.setPaidAmount(BigDecimal.ZERO);
        //EMPTY_OTHER_CAPITAL.setIncomeAmount(BigDecimal.ZERO);
    }


    /**
     * 账号表
     */
    @Resource
    private TblReceiveRefundAccountMapper tblReceiveRefundAccountMapper;

    /**
     * 店铺表
     */
    @Resource
    private TblReceiveRefundShopMapper tblReceiveRefundShopMapper;

    /**
     * 其他货币资金日记账
     */
    @Resource
    private TblRrOtherCapitalDetailMapper tblRrOtherCapitalDetailMapper;

    /**
     * 统一报表
     */
    @Resource
    private TblUnificationBillDetailMapper tblUnificationBillDetailMapper;

    /**
     * 优购资金账单
     */
    @Resource
    private TblYgXcxCapitalBillMapper tblYgXcxCapitalBillMapper;

    /**
     * 微信小程序
     */
    @Resource
    private TblWcXcxCapitalBillMapper tblWcXcxCapitalBillMapper;

    /**
     * 蘑菇街小程序
     */
    @Resource
    private TblMgjXcxCapitalBillMapper tblMgjXcxCapitalBillMapper;

    /*@Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public void refresh(List<String> ncVirtualAccounts) throws ServiceException {
        try {
            if (CollectionUtils.isEmpty(ncVirtualAccounts)) {
                return;
            }

            List<TblRrOtherCapitalDetail> list = tblRrOtherCapitalDetailMapper.getList(ncVirtualAccounts);
            List<List<TblRrOtherCapitalDetail>> listList = devideGroup(list);
            for (List<TblRrOtherCapitalDetail> details : listList) {
                refreshDetails(details);
            }
        } catch (Exception ex) {
            throw new ServiceException("刷新异常", ex);
        }
    }*/

    /**
     * 刷新明细
     *
     * @param details
     */
    /*private void refreshDetails(List<TblRrOtherCapitalDetail> details) throws ParseException {

        sortOrderByMonth(details);

        TblRrOtherCapitalDetail detail = details.get(0);
        TblReceiveRefundAccount account = getAccount(detail);

        if (null == account) {
            return;
        }


        TblReceiveRefundShop shop = null;
        if(org.apache.commons.lang3.StringUtils.isNotEmpty(account.getNcShopNo())){
                shop = tblReceiveRefundShopMapper.getShop(account.getNcShopNo());
        }

        OtherCapitalStatisticsParam param = getStatisticsParam(detail, account, shop);

        for (TblRrOtherCapitalDetail info : details) {
            param.setStartDate(getFirstDayOfMonth(info.getCapitalMonth()));
            param.setEndDate(getLastDayOfMonth(info.getCapitalMonth()));
            OtherCapitalStatistics statistics = getOtherCapitalStatistics(param);
            if (statistics != null) {
                info.setIncomeAmount(statistics.getIncomeAmount());
                info.setPaidAmount(statistics.getPaidAmount());
            }
        }

        calculateAmount(details);
        updateOtherCapitalDetails(details);

    }*/

    /**
     * 获取账号
     *
     * @param detail
     * @return
     */
    /*private TblReceiveRefundAccount getAccount(TblRrOtherCapitalDetail detail) {
        List<TblReceiveRefundAccount> accounts = tblReceiveRefundAccountMapper.getAccount(detail.getNcVirtualAccount(),
                detail.getCheckAccountBookNo(), detail.getNcShopNo());

        for (TblReceiveRefundAccount account : accounts) {
            if ("Y".equals(account.getIsCapitalAccount())) {
                return account;
            }
        }
        return null;
    }*/

    /**
     * 更新数据
     *
     * @param details
     */
    private void updateOtherCapitalDetails(List<TblRrOtherCapitalDetail> details) {
        for (TblRrOtherCapitalDetail detail : details) {
            tblRrOtherCapitalDetailMapper.update(detail);
        }
    }

    /**
     * 计算各种金额
     *
     * @param details
     */
    /*private void calculateAmount(List<TblRrOtherCapitalDetail> details) {
        TblRrOtherCapitalDetail lastOtherCapital = EMPTY_OTHER_CAPITAL;
        for (TblRrOtherCapitalDetail detail : details) {

            BigDecimal beginBalace = null;
            if (lastOtherCapital == EMPTY_OTHER_CAPITAL) {
                beginBalace = getNotEmpty(detail.getBeginBalance());
            } else {
                beginBalace = getNotEmpty(lastOtherCapital.getSettleAmount());
            }
            detail.setBeginBalance(beginBalace);

            BigDecimal settleAmount =
                    beginBalace.add(getNotEmpty(detail.getPaidAmount())).add(getNotEmpty(detail.getIncomeAmount()));
            detail.setSettleAmount(settleAmount);

            BigDecimal diffAmount = settleAmount.subtract(getNotEmpty(detail.getPageRemainAmount()));
            detail.setDiffAmount(diffAmount);

            lastOtherCapital = detail;
        }
    }*/

    /**
     * 获取非空的 decimal
     *
     * @param decimal
     * @return
     */
    private BigDecimal getNotEmpty(BigDecimal decimal) {
        if (null == decimal) {
            return BigDecimal.ZERO;
        }
        return decimal;
    }

    /**
     * 获取统计数据
     *
     * @param param
     * @return
     */
    private OtherCapitalStatistics getOtherCapitalStatistics(OtherCapitalStatisticsParam param) {
        final String weChatPlatfrom = "微信平台";
        if (weChatPlatfrom.equals(param.getWebsiteUrl())) {

            if (ChannelEnum.YG.getNo().equals(param.getChannelNo())) {
                return tblYgXcxCapitalBillMapper.statisticsAmount(param);
            }

            if (ChannelEnum.XCXWC.getNo().equals(param.getChannelNo())) {
                return tblWcXcxCapitalBillMapper.statisticsAmount(param);
            }

            if (ChannelEnum.XCXMG.getNo().equals(param.getChannelNo())) {
                return tblMgjXcxCapitalBillMapper.statisticsAmount(param);
            }

        }
        return tblUnificationBillDetailMapper.statisticsAmount(param);
    }

    /**
     * 组装统计的请求参数
     *
     * @param detail  其他货币资金日记账
     * @param account 账号
     * @return
     */
    /*private OtherCapitalStatisticsParam getStatisticsParam(TblRrOtherCapitalDetail detail,
                                                           TblReceiveRefundAccount account,
                                                           TblReceiveRefundShop shop) {
        OtherCapitalStatisticsParam param = new OtherCapitalStatisticsParam();

        param.setNcVirtualAccount(detail.getNcVirtualAccount());
        param.setCheckAccountBookNo(detail.getCheckAccountBookNo());

        param.setNcEnterAccountBody(account.getNcEnterAccountBody());
        param.setChannelNo(account.getChannelNo());
        param.setWebsiteUrl(account.getWebsiteUrl());

        if (shop != null) {
            param.setShopNo(shop.getShopNo());
        }

        if (!StringUtils.isEmpty(param.getChannelNo())) {
            param.setBillType(channalNoVBillTypeNameMap.get(param.getChannelNo()));
        }

        return param;
    }*/

    /**
     * 按照 虚拟账号和 核算账簿编码 进行分组
     *
     * @param list
     * @return
     */
    /*private List<List<TblRrOtherCapitalDetail>> devideGroup(List<TblRrOtherCapitalDetail> list) {
        Map<String, List<TblRrOtherCapitalDetail>> map = new HashMap<>(16);
        for (TblRrOtherCapitalDetail info : list) {
            String key = info.getNcVirtualAccount() + "_" + info.getCheckAccountBookNo() + "_" + info.getNcShopNo();
            if (!map.containsKey(key)) {
                map.put(key, new ArrayList<>());
            }
            map.get(key).add(info);
        }
        List<List<TblRrOtherCapitalDetail>> lists = new ArrayList<>();
        for (Map.Entry<String, List<TblRrOtherCapitalDetail>> entry : map.entrySet()) {
            lists.add(entry.getValue());
        }
        return lists;
    }*/

    /**
     * 按照月份对数据进行排序
     *
     * @param list
     */
    /*private void sortOrderByMonth(List<TblRrOtherCapitalDetail> list) {
        Collections.sort(list, new Comparator<TblRrOtherCapitalDetail>() {
            @Override
            public int compare(TblRrOtherCapitalDetail o1, TblRrOtherCapitalDetail o2) {
                return o1.getCapitalMonth().compareTo(o2.getCapitalMonth());
            }
        });
    }*/

    /**
     * 获取月份的第一天
     *
     * @return
     */
    private Date getFirstDayOfMonth(String month) throws ParseException {
        return DateUtils.parseDate(month + "01", "yyyyMMdd");
    }

    /**
     * 获取月份的最后一天
     *
     * @param month
     * @return
     */
    private Date getLastDayOfMonth(String month) throws ParseException {
        Date date = getFirstDayOfMonth(month);
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.MONTH, 1);
        calendar.add(Calendar.SECOND, -1);
        return calendar.getTime();
    }

}
